package com.vteba.security.meta;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.vteba.common.constant.CommonConst;
import com.vteba.security.user.Authority;

public class ConfigAttributeImpl implements ConfigAttribute {
	private static final long serialVersionUID = 7646921150051494711L;
	private final String attribute;
	private String authName;
	private String tenantId;
	
	public ConfigAttributeImpl(Authority authority) {
		Assert.notNull(authority);
		String authName = authority.getAuthName();
		Assert.hasText(authName, "authName cannot be null.");
		String tenantId = authority.getTenantId();
		this.authName = authName;
		this.tenantId = tenantId;
		if (tenantId != null) {
			this.attribute = authName + CommonConst.SHARP + tenantId;
		} else {
			this.attribute = authName;
		}
	}
	
	public ConfigAttributeImpl(String authName) {
		Assert.hasText(authName, "You must provide a configuration attribute");
		this.attribute = authName;
		this.authName = authName;
	}
	
	public ConfigAttributeImpl(String authName, String tenantId) {
		Assert.hasText(authName, "You must provide a configuration attribute");
		if (tenantId != null) {
			this.attribute = authName + CommonConst.SHARP + tenantId;
		} else {
			this.attribute = authName;
		}
		this.authName = authName;
		this.tenantId = tenantId;
	}

	public boolean equals(Object obj) {
		if (obj instanceof ConfigAttribute) {
			ConfigAttribute attr = (ConfigAttribute) obj;
			return this.attribute.equals(attr.getAttribute());
		}
		return false;
	}

	public String getAttribute() {
		return this.attribute;
	}

	public int hashCode() {
		return this.attribute.hashCode();
	}

	public String toString() {
		return this.attribute;
	}

	public static List<ConfigAttribute> createListFromCommaDelimitedString(String access) {
		return createList(StringUtils.commaDelimitedListToStringArray(access));
	}

	public static List<ConfigAttribute> createList(String... attributeNames) {
		Assert.notNull(attributeNames, "You must supply an array of attribute names");
		List<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>(
				attributeNames.length);

		for (String attribute : attributeNames) {
			attributes.add(new SecurityConfig(attribute.trim()));
		}

		return attributes;
	}

	public String getAuthName() {
		return authName;
	}

	public void setAuthName(String authName) {
		this.authName = authName;
	}

	public String getTenantId() {
		return tenantId;
	}

	public void setTenantId(String tenantId) {
		this.tenantId = tenantId;
	}
}
